package com.Jian.reggie.filter;

import com.Jian.reggie.common.BaseContext;
import com.Jian.reggie.common.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: LoginCheckFilter
 * Package: com.Jian.reggie.filter
 * Description:
 *
 * @Author 蹇泽阳
 * @Create 2023/11/25 8:50
 * @Version 1.0
 */
// 检查用户是否已经完成登录
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = {"/*"})
public class LoginCheckFilter implements Filter {
  //  路径匹配器，支持通配符
  public static final AntPathMatcher antPathMatcher = new AntPathMatcher();
  
  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse resp = (HttpServletResponse) servletResponse;
    log.info("拦截到请求：{}", req.getRequestURI());
    
    // 获取本次请求URI
    String requestURI = req.getRequestURI();
    // 定义白名单
    String[] whiteList = {"/employee/login", "/employee/logout", "/backend/**", "/front/**", "/common/**","/user/sendMsg","/user/login"};
    // 检查是否在白名单中
    if (check(requestURI, whiteList)) {
      // 放行
      filterChain.doFilter(req, resp);
      return;
    }
    // 如果不在白名单中，检查是否已经登录
    Object employee = req.getSession().getAttribute("employee");
    Object user = req.getSession().getAttribute("user");
    if (employee != null) {
      BaseContext.setCurrentId((Long) employee);
      // 放行
      filterChain.doFilter(req, resp);
      return;
    }
    if (user != null) {
      BaseContext.setCurrentId((Long) user);
      // 放行
      filterChain.doFilter(req, resp);
      return;
    }
    // 如果没有登录，返回未登录结果
    resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));// NOTLOGIN是前端定义的
    return;
  }
  
  public boolean check(String requestURI, String[] whiteList) {
    for (String pattern : whiteList) {
      if (antPathMatcher.match(pattern, requestURI)) {
        return true;
      }
    }
    return false;
  }
}

